package com.iflysse.servlet.user;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iflysse.pojo.MenuInfo;
import com.iflysse.pojo.Node;
import com.iflysse.pojo.TreeJson;
import com.iflysse.servlet.util.BaseServlet;

/**
 * Servlet implementation class ShowUserRoleServlet
 */
@WebServlet("/user/ShowUserRoleServlet.do")
public class ShowUserRoleServlet extends BaseServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		createTreeJson(request, response);

	}

	/**
	 * 生成当前用户权限的树形结构 modify by wuyigang
	 * 
	 * @param request
	 * @param response
	 */
	private void createTreeJson(HttpServletRequest request,
			HttpServletResponse response) {
		
		List<Node> nodes = (List<Node>) request.getSession().getAttribute("menu");
		List<TreeJson> flist = new ArrayList<TreeJson>();
		for(Node node:nodes){
			TreeJson tj1 = new TreeJson();
			MenuInfo fmenu = node.getMenuIno();
			tj1.setId(fmenu.getMenuId());
			tj1.setText(fmenu.getMenuName());
			
			List<MenuInfo> clist = node.getList();
			List<TreeJson> ctrees = new ArrayList<TreeJson>();
			for(MenuInfo m:clist){
				TreeJson tj2 = new TreeJson();
				tj2.setId(m.getMenuId());
				tj2.setText(m.getMenuName());
				ctrees.add(tj2);
			}
			tj1.setChildren(ctrees);
			flist.add(tj1);
		}
		
//		System.out.println(flist);

		try {
			print2Page(response, flist.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void print2Page(HttpServletResponse resp, String json)
			throws IOException {
		resp.setContentType("application/json;charset=UTF-8");
		Writer writer = resp.getWriter();
		writer.write(json);
		writer.flush();
	}
}
